<template>
	<div>
		<view>
			<div class="content" :class="[disabled ? 'disabled' : '']" @click.stop="open">
				<div class="text" :class="[labelOverflow ? 'text-overflow' : '']">
					{{ currentLabel }}
				</div>
				<div class="icon" v-if="canSelect">
					<uni-icons type="forward" size="18"></uni-icons>
				</div>
			</div>
			<!-- 普通弹窗 -->
			<uni-popup
				:isMaskClick="isMaskClick"
				ref="popup"
				background-color="#fff"
				@close="close"
				@maskClick="close">
				<div class="container">
					<!-- 搜索栏 -->
					<div class="topContainer">
						<div class="btn cancel" @click="cancel">取消</div>
						<div class="search" v-if="showFilter">
							<uni-search-bar
								v-model="searchText"
								class="uni-mt-10"
								radius="5"
								placeholder="请输入过滤内容"
								clearButton="auto"
								cancelButton="none"
								@input.stop="inputHandler" />
						</div>
						<div class="btn sure" @click.stop="next" v-if="showNext">下一步</div>
						<div class="btn sure" @click.stop="sure" v-else>确认</div>
					</div>
					<div class="tab">
						<div
							class="tab-item"
							:class="[activedTab == index ? 'active' : '']"
							v-for="(item, index) in dictList"
							:key="index"
							@click="changeTab(index)">
							<div class="label">
								{{ getDictLabel(item) }}
							</div>
						</div>
					</div>
					<div class="options">
						<div class="loading" v-if="activedTree.loading">
							<div class="icon">
								<uni-icons type="spinner-cycle" size="24"></uni-icons>
							</div>
							<text>加载中...</text>
						</div>
						<div v-else>
							<picker-view
								v-if="activedListCopy.length > 0"
								:value="index"
								@change="bindChange"
								class="picker-view"
								:immediate-change="true"
								ref="pickerView">
								<picker-view-column>
									<view class="item" v-for="(item, index) in activedListCopy">
										{{ getDictLabel(item) }}
									</view>
								</picker-view-column>
							</picker-view>
							<div v-else class="emptyContent">无数据</div>
						</div>
					</div>
				</div>
			</uni-popup>
		</view>
	</div>
</template>

<script>
	export default {
		name: '',
		components: {},
		props: {
			value: {
				required: false,
			},
			state: {
				required: false,
				default: 'write',
			},
			disabled: {
				required: false,
			},
			dict: {
				required: false,
				default: () => {},
			},
			label: {
				required: false,
			},
			labelOverflow: {
				type: Boolean,
				default: false,
			},
			format: {
				required: false,
				type: Function,
			},
			showFilter: {
				type: Boolean,
				default: true,
			},
			joinSymbol: {
				type: String,
				default: '/',
			},
			placeholder: {
				type: String,
			},
			isMaskClick: {
				type: Boolean,
				default: true,
			},
		},
		data() {
			return {
				index: [0],
				current: undefined,
				dictList: [],
				activedListCopy: [],
				searchText: undefined,
				activedTab: 0,
				rawValue: [],
			};
		},
		computed: {
			showNext() {
				return this.activedTab < this.dictList?.length - 1;
			},
			activedTree() {
				return this.dictList?.[this.activedTab] ?? {};
			},
			activedList() {
				return this.dictList?.[this.activedTab]?.children ?? [];
			},
			labels() {
				let words = [];
				this.rawValue?.map((item, index) => {
					let currentTree = this.dictList[index];
					let currentTreeItem = currentTree?.children?.find(
						child => item === this.getDictValue(child),
					);
					let currentTreeItemLabel = this.getDictLabel(currentTreeItem);

					words.push(currentTreeItemLabel ?? '-');
				});
				return words;
			},
			currentLabel() {
				let word = '';
				if (this.Empty(this.format)) {
					this.labels?.map((item, index) => {
						if (index == this.rawValue.length - 1) {
							word += `${item ?? '-'}`;
						} else {
							word += `${item ?? '-'} ${this.joinSymbol} `;
						}
					}, word);
				} else {
					word = this.format(this.labels);
				}
				let defaultWord = this.state == 'readonly' ? '-' : this.placeholder ?? '请选择数据';
				word = this.label ?? word ?? defaultWord;
				return word;
			},

			dictValue() {
				return this.dict?.value ?? 'value';
			},
			dictLabel() {
				return this.dict?.label ?? 'label';
			},

			canSelect() {
				return (this.state == 'write' || this.Empty(this.state)) && this.disabled != true;
			},
		},
		created() {},
		watch: {
			dict: {
				handler: function (val) {
					this.initDict();
				},
				immediate: true,
			},
		},
		mounted() {},
		methods: {
			changeTab(index) {
				this.activedTab = index;
				this.activedListCopy = this.activedList;
				this.$nextTick(() => {
					this.index = [0];
				});
			},
			close() {
				this.$refs.popup.close();
				this.$nextTick(() => {
					this.reset();
				});
			},
			inputHandler(e) {
				this.activedListCopy = this.activedList;
				if (this.Empty(this.searchText)) {
					return;
				}
				let list = this.activedList?.filter(item => {
					return this.getDictLabel(item).indexOf(this.searchText) !== -1;
				});
				this.activedListCopy = list;
				this.$nextTick(() => {
					this.index = [0];
				});
			},
			open() {
				if (this.canSelect) {
					this.$emit('open');
					this.$refs.popup.open('bottom');
					this.$nextTick(() => {
						this.$emit('opened');
					});
				}
			},

			initDict() {
				if (Array.isArray(this.dict?.list) && this.dict?.list?.length > 0) {
					let dictList = this.A_deepClone(this.dict.list ?? []);
					if (typeof dictList[0] !== 'object') {
						this.type = 'stringArr';
						dictList = [];
						this.dict?.list?.map(item => {
							dictList.push({
								value: item,
								text: item,
							});
						});
					}

					dictList?.map(item => {
						item.text = this.getDictLabel(item);
						item.value = this.getDictValue(item);
					});
					this.dictList = dictList;
					this.$nextTick(() => {
						this.activedListCopy = this.activedList;
					});
				}
			},
			bindChange(e) {
				this.index = e.detail.value;
				// this.$emit('bindChange', this.dict.list?.[e.detail.value]);
			},
			next() {
				this.setSelectData();
				this.activedTab += 1;
				this.searchText = '';
				this.$emit('next', {
					step: this.activedTab,
					value: this.rawValue,
				});
			},
			sure() {
				this.setSelectData();
				this.$emit('input', this.rawValue);
				this.$emit('sure', {
					value: this.rawValue,
					labels: this.labels,
				});
				this.$refs.popup.close();
			},
			setSelectData() {
				this.$set(
					this.rawValue,
					this.activedTab,
					this.getDictValue(this.activedListCopy?.[this.index?.[0]]),
				);
				this.$nextTick(() => {
					this.index = [0];
				});
			},
			cancel() {
				this.reset();
				this.$refs.popup.close();
			},
			getDictLabel(data) {
				if (typeof data !== 'object') {
					return data;
				}
				return (
					data?.[this.dict?.label] ??
					data?.[this.activedTree?.label] ??
					data?.dictLabel ??
					data?.label ??
					data?.text
				);
			},
			getDictValue(data) {
				if (typeof data !== 'object') {
					return data;
				}
				return (
					data?.[this.dict?.value] ??
					data?.[this.activedTree?.value] ??
					data?.dictValue ??
					data?.value
				);
			},
			reset() {
				console.log('reset');
				this.rawValue = [];
				this.activedTab = 0;
				this.index = [0];
				this.searchText = '';
			},
		},
	};
</script>

<style lang="scss" scoped>
	.uni-input {
		line-height: 30rpx;
		margin-left: 10rpx;
	}
	.container {
		padding: 20rpx 20rpx 0 20rpx;
		.topContainer {
			display: flex;
			justify-content: space-between;
			align-items: center;
			.search {
				flex: 1;
				min-width: 0;
			}
		}
		.options {
			margin-top: 20rpx;
			display: flex;
			flex-direction: column;
			gap: 0 20rpx;
			position: relative;
			width: 750rpx;
			height: 400rpx;
			.item {
				text-align: center;
			}
			.picker-view {
				width: 750rpx;
				height: 400rpx;
			}
			.emptyContent {
				width: 750rpx;
				height: 400rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}
			.loading {
				width: 750rpx;
				height: 400rpx;
				position: absolute;
				display: flex;
				justify-content: center;
				align-items: center;
				.icon {
					animation: rotate360 5s linear infinite;
				}
			}
		}
	}
	.content {
		min-height: 32px;
		display: flex;
		align-items: center;
		.text {
			flex: 1;
			min-width: 0;
		}
		.text-overflow {
			text-overflow: ellipsis;
			overflow: hidden;
			word-break: break-all;
			white-space: nowrap;
		}
		.icon {
			margin-left: 15rpx;
		}
	}
	.disabled {
		color: #606266;
	}
	.tab {
		display: flex;
		.tab-item {
			display: flex;
			padding: 15rpx 25rpx;
			.label {
				max-width: 100px;
				text-overflow: ellipsis;
				overflow: hidden;
				word-break: break-all;
				white-space: nowrap;
			}
		}
		.active {
			border-bottom: 5px solid #69a1fa;
		}
	}
	@keyframes rotate360 {
		0% {
			transform: rotate(0deg);
		}
		100% {
			transform: rotate(360deg);
		}
	}
</style>
